#!/usr/bin/perl -w
#
# autor:Manuel Hevia
# description: 
#   make_out.txt -> .abidos_cpp/files_input
#
#-------------------------------------------
use strict;

my $dir = '.abidos_cpp';

sub create_directories
{
  my @directories = ($dir);

  foreach (@directories) {
    print "  checking existence $_ ...";

    unless(-d $_){
        print "creating...";
        mkdir $_ or die "  Couldn't create dir: [$_]\n";
        print "[ok]\n";
    }
    else
    {
        print "[ok]\n";
    }
  }
}

sub generate_loader_file
{
  my $file_input_name = "make_out.txt";
  #the output for this scripts the input for abidos parser
  my $file_output_name = "$dir/files_input";
  
  open(f_in,"< $file_input_name") or die("error open < $file_input_name");
  my @raw_data=<f_in>;
  open(f_out,"> $file_output_name") or die("error open > $file_output_name");

  printf f_out "#\n";
  printf f_out "# generated by abidos\n";
  printf f_out "# this file is for the loader of abidos processor\n";
  printf f_out "#\n";

  foreach my $l (@raw_data) {
    chomp($l);
    $_= $l;

    my @directories = ();
    if( $_ =~ /^(g++|cc|c++)/ ) {
      if( $_ !~ /-c/ ) {
        next;
      }

#      printf f_out "#$_\n";
      #we are in a line like this:
      #g++ -Wall -c -g -I../includes trace.cpp
	    while ($_ =~ m/-I([\S]+)/g) {
	      my $d = $1;
	      if( $d =~ /\/$/) {
	        chop($d);
        }

        push(@directories, $d);
	    }

      if( $_ = /[^\-]([\S]+)\.(cpp|cc)(\s|$)/) {
        #../../preprocessor/ts.cpp:../../preprocessor:../includes:.
        my $file = $1.'.'.$2;
	      if ($file =~ m/([\S]+)\/([\S]+)\.(cpp|cc)/g) {
          push(@directories, $1);
          my $str = join(':', @directories);
          print f_out "$1/$2.$3:$str\n";
	      } else {
          my $str = join(':', @directories);
          print f_out "$1.$2:$str\n";
        }
      } else {
        print f_out "#no cpp file [$l]\n";
      }
    }
  }

  close(f_in);
  close(f_out);
}

sub process_project
{
  system ("/opt/abidos_cpp/abidos_cpp --test_all_tokens_consumed_flag --no_std --out_dir .abidos_cpp --loader .abidos_cpp/files_input") == 0 or die "system failed: $?";
  system ("/opt/abidos_cpp/xdot_run.py .abidos_cpp/files_output.dot") == 0 or die "system failed: $?";
}

sub main
{
  my $num_args = $#ARGV;

  if ($num_args != 0) {
    print "\n no --debug mode\n";
  }

  create_directories();
  generate_loader_file();
  if ($num_args != 0) {
    process_project();
  }
}

main();
